package com.usian.comment.service.impl;

import com.usian.comment.feign.ApUserFeign;
import com.usian.comment.service.ApCommentService;
import com.usian.model.comment.dtos.CommentDto;
import com.usian.model.comment.dtos.CommentLikeDto;
import com.usian.model.comment.dtos.CommentSaveDto;
import com.usian.model.comment.pojos.ApComment;
import com.usian.model.comment.pojos.ApCommentLike;
import com.usian.model.comment.pojos.ApCommentVo;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.pojos.ApUser;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ApCommentServiceImpl implements ApCommentService {

    @Autowired
    private ApUserFeign apUserFeign;
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public ResponseResult saveComment(CommentSaveDto dto) {

        if(dto==null || StringUtils.isBlank(dto.getContent())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if(StringUtils.isNotBlank(dto.getContent()) && dto.getContent().length()>100){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"评论内容长度不能大于100");
        }

        Integer userid =null;
        ApUser apUser = AppThreadLocalUtils.getUser();
        if(apUser!=null){
            userid = apUser.getId();
        }

        ApUser apUser1 = apUserFeign.findById(userid);
        if(apUser1==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        ApComment apComment = new ApComment();
        apComment.setAuthorId(userid);
        apComment.setAuthorName(apUser1.getName());
        apComment.setContent(dto.getContent());
        apComment.setEntryId(dto.getArticleId());
        apComment.setCreatedTime(new Date());
        apComment.setUpdatedTime(new Date());
        apComment.setImage(apUser1.getImage());
        apComment.setLikes(0);
        apComment.setReply(0);
        apComment.setType((short) 0);
        apComment.setFlag((short) 0);
        mongoTemplate.save(apComment);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult saveCommentLike(CommentLikeDto dto) {
        if(dto==null || StringUtils.isBlank(dto.getCommentId()) || dto.getOperation() ==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        Integer userid =null;
        ApUser apUser = AppThreadLocalUtils.getUser();
        if(apUser!=null){
            userid = apUser.getId();
        }

        //判断是点赞  取消点赞
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        if(apComment ==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"评论数据不存在");
        }

        if(dto.getOperation()==0){
            //点赞
            apComment.setLikes(apComment.getLikes()+1);
            mongoTemplate.save(apComment);

            ApCommentLike apCommentLike =new ApCommentLike();
            apCommentLike.setAuthorId(userid);
            apCommentLike.setCommentId(apComment.getId());
            apCommentLike.setOperation(Short.valueOf(dto.getOperation().toString()));
            mongoTemplate.save(apCommentLike);

        }else if(dto.getOperation()==1){
            apComment.setLikes(apComment.getLikes()<=0? 0: apComment.getLikes()-1);
            mongoTemplate.save(apComment);

            Query query = Query.query(Criteria.where("authorId").is(userid).and("commentId").is(apComment.getId()));
            mongoTemplate.remove(query,ApCommentLike.class);
        }

        Map<String,Object> map =new HashMap<>();
        map.put("like",apComment.getLikes());
        return ResponseResult.okResult(map);
    }

    @Override
    public ResponseResult findByArticleId(CommentDto dto) {
        //1.检查参数
        if(dto.getArticleId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        int size = 10;

        //2.按照文章id过滤，设置分页和排序
        Query query = Query.query(Criteria.where("entryId").is(dto.getArticleId()));
        query.limit(size).with(Sort.by(Sort.Direction.DESC,"createdTime"));
        List<ApComment> list = mongoTemplate.find(query, ApComment.class);

        //3.数据封装返回
        //3.1 用户未登录 加载数据
        ApUser user = AppThreadLocalUtils.getUser();
        if(user== null){
            return ResponseResult.okResult(list);
        }

        //3.2 用户已登录，加载数据，需要判断当前用户点赞了哪些评论
        List<String> idList = list.stream().map(x -> x.getId()).collect(Collectors.toList());
        Query query1 = Query.query(Criteria.where("commentId").in(idList).and("authorId").is(user.getId()));
        List<ApCommentLike> apCommentLikes = mongoTemplate.find(query1, ApCommentLike.class);

        List<ApCommentVo> resultList = new ArrayList<>();

        if(list!=null && apCommentLikes!=null){

            for(ApComment apComment: list){
                ApCommentVo apCommentVo = new ApCommentVo();
                BeanUtils.copyProperties(apComment, apCommentVo);

                for (ApCommentLike apCommentLike : apCommentLikes) {
                    if (apComment.getId().equals(apCommentLike.getCommentId())) {

                        //标识该条评论是点赞过的
                        apCommentVo.setOperation((short) 0);
                        break;
                    }
                }
                resultList.add(apCommentVo);
            }
            /*list.stream().forEach(x -> {

            });*/

            return ResponseResult.okResult(resultList);
        }else {
            return ResponseResult.okResult(list);
        }
    }
}
